<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>反弹球</title>
    <style>
        .container{
            width: 800px;
            height: 600px;
            border: 3px solid black;
            margin: 0 auto;
            position: relative;
        }

        .ball{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: #005ea7;
            border-radius: 50%;
            left: 0px;
            top: 0px;
        }
    </style>
</head>
<body>
    <div>
        <button onclick="start()">开始</button>
        <button onclick="stop()">停止</button>
    </div>
    <div class="container" id="container">
        <div class="ball" id="ball"></div>
    </div>
    <script>

        let timer = null
        let horizontal = 'right'
        let vertical = 'bottom'

        function start(){
            const ball = document.getElementById("ball")

            timer = setInterval(function (){
                const style = window.getComputedStyle(ball)
                //水平方向
                let left = parseInt(style.left)
                if(left >= 800-100){
                    horizontal = 'left'
                }else if(left <= 0){
                    horizontal = 'right'
                }
                if(horizontal == 'right') {
                    left += 5
                }else{
                    left -= 5
                }
                //垂直方向
                let top = parseInt(style.top)
                if(top >= 600-100){
                    vertical = 'top'
                }else if(top <= 0){
                    vertical = 'bottom'
                }
                if(vertical == 'bottom') {
                    top += 5
                }else{
                    top -= 5
                }

                ball.style.left = left + 'px'
                ball.style.top = top + 'px'
                console.log(left,top)
            },10)

        }

        function stop(){
            clearInterval(timer)
            timer = null
        }
    </script>
</body>
</html>